package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.ShopCarItem;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IShopCarService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("sessions")
public class SessionController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IShopCarService shopCarService;
    @PostMapping()
    public JsonResult login(@RequestParam String email, @RequestParam String password){
        JsonResult result = new JsonResult();
        try {
            User user = userService.login(email, password);
            UserContext.setCurrentUser(user);
            result.setResult(user);
            //登录后马上查询出 购物车内容
            Map<Long, ShopCarItem> car = shopCarService.selectForUserId(user.getId());


            result.setResultTwo(car);
            UserContext.setCurrentUserShopCar(car);
        } catch (Exception e) {
            result.mark(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    @DeleteMapping
    public JsonResult logout(){
        JsonResult result = new JsonResult();
        UserContext.getSession().invalidate();
        return result;
    }

    /**
     * 加入购物车的
     * @param productId  商品id
     * @param count 商品数量
     * @return
     */
    @PutMapping("car/addItem")
    public JsonResult addItem(Long productId, Integer count){
        JsonResult result = new JsonResult();
        shopCarService.addshopItem(productId,count);
        result.setResultTwo(UserContext.getCurrentUserShopCar());
        return result;
    }
    /**
     * 点击购物中的页面后 的 对已在购物车的商品进行 减法
     * @param productId  商品id
     * @return
     */
    @PutMapping("car/subProductCount")
    public JsonResult subProductCount(Long productId){
        JsonResult result = new JsonResult();
        shopCarService.subProductCount(productId);
        result.setResultTwo(UserContext.getCurrentUserShopCar());
        return result;
    }
    /**
     * 删除整个购物车项
     * @param productId
     * @return
     */
    @PutMapping("car/deleteItem")
    public JsonResult deleteItem(Long productId){
        JsonResult result = new JsonResult();
        shopCarService.deleteItem(productId);
        result.setResultTwo(UserContext.getCurrentUserShopCar());
        return result;
    }
    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("car/clear")
    public JsonResult deletecar(){
        JsonResult result = new JsonResult();
        shopCarService.deleteCarItem();
        return result;
    }
}
